package com.smart.register.service.zookeeper;

import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.data.Stat;

import com.smart.register.service.IServiceRegister;
import com.smart.register.service.ServiceConfig;
import com.smart.register.utils.RegisterDict;
import com.smart.register.utils.ResourcesUtils;

public class ZkServiceRegister implements IServiceRegister {
	
	public boolean registerService(ServiceConfig config) {
		System.out.println(">>开始注册服务...");
		String url = ResourcesUtils.getValue(RegisterDict.app_url);
		String weight = ResourcesUtils.getValue(RegisterDict.app_weight);
		String system = ResourcesUtils.getValue(RegisterDict.app_system_name);
		
		CuratorFramework client = ZkClient.getInstance();
		try {
			//检测节点目录是否存在
			String node = toZkNode(system, config.getUri());
			String hessian = toHessianUrl(url, config.getUri());
			Stat stat = client.checkExists().forPath(node);
			if(stat == null){
				client.create().forPath(node, hessian.getBytes("UTF-8"));
			}
			client.setData().forPath(node, hessian.getBytes("UTF-8"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(">>结束注册服务...");
		return true;
	}
	
	private String toZkNode(String system, String uri){
		StringBuffer node = new StringBuffer();
		if(system == null || "".equals(system)){
			node.append("/smart");
		}else if(!system.startsWith("/")){
			node.append("/").append(system);
		}
		
		if(!uri.startsWith("/")){
			node.append("/").append(uri);
		}else{
			node.append(uri);
		}
		return node.toString();
	}
	
	private String toHessianUrl(String url, String uri){
		if(url.endsWith("/") && uri.startsWith("/")){
			return url.substring(url.length(), url.length() -1).concat(uri);
		}else if(url.endsWith("/") && !uri.startsWith("/")){
			return url.concat(uri);
		}else if(!url.endsWith("/") && uri.startsWith("/")){
			return url.concat("/").concat(uri.substring(1));
		}else{
			return url.concat("/").concat(uri);
		}
	}
}
